package com.aifast.common.desensitize;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

public class AiFastDesensitizeSerializer extends JsonSerializer<String> implements ContextualSerializer {

    private DesensitizeType dese;

    public AiFastDesensitizeSerializer() {
    }

    public AiFastDesensitizeSerializer(DesensitizeType type) {
        this.dese = type;
    }

    @Override
    public void serialize( String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeString(dese.function().apply(value));
    }

    @Override
    public JsonSerializer<?> createContextual(final SerializerProvider prov, final BeanProperty property) throws JsonMappingException {
//        Console.log(prov);
//        Console.log(property);
        Desensitize annotation = property.getAnnotation(Desensitize.class);
        Map<String, String> map = Desensitizer.get();
        if (ObjectUtil.isNotNull(annotation) && Objects.equals(property.getType().getRawClass(), String.class) && (ObjectUtil.isNull(map) || !map.containsKey("skip") || !StrUtil.equals("yes",map.get("skip")))) {
            this.dese = annotation.value();
            return this;
        }
        Desensitizer.remove();
        return prov.findValueSerializer(property.getType(), property);
    }
}
